package com.ziq.base.base

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.animation.*
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import com.ziq.base.R

abstract class BaseDialog(context: Context, themeResId : Int = 0) : Dialog(context, themeResId) , LifecycleOwner {

    var mAnimationDuration = 200
    var mIsAnimating = false
    var animateTargetView :View? = null
    var mLifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)

    override fun onStart() {
        super.onStart()
        window?.let {
            it.setWindowAnimations(R.style.FwBaseDialog)
            window?.decorView?.setPadding(0, 0, 0, 0)
            val params = window!!.attributes
            params.width  = initWidth()
            params.height = initHeight()
            params.gravity = initGravity()
            window!!.attributes = params
            window!!.setBackgroundDrawableResource(android.R.color.transparent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
    }


    override val lifecycle: Lifecycle
        get() = mLifecycleRegistry


    open fun initGravity() :Int{
        return Gravity.CENTER
    }

    open fun initWidth() :Int{
        return ViewGroup.LayoutParams.WRAP_CONTENT
    }

    open fun initHeight() :Int{
        return ViewGroup.LayoutParams.WRAP_CONTENT
    }

    fun setAnimateView(target: View){
        this.animateTargetView = target
    }


    override fun show() {
        if ((context is Activity) && (context as Activity).isFinishing){
            return
        }
        super.show()
        if(animateTargetView != null){
            animateShow()
        }
    }

    override fun dismiss() {
        if(animateTargetView != null){
            if (mIsAnimating) {
                return
            }
            animateHide()
        }else {
            mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE)
            mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
            super.dismiss()
        }
    }

    open fun dialogDismiss(){
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE)
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        super.dismiss()
    }

    open fun getShowAnimationSet(): AnimationSet{
        val translate =
            TranslateAnimation(
                Animation.RELATIVE_TO_SELF,
                0f,
                Animation.RELATIVE_TO_SELF,
                0f,
                Animation.RELATIVE_TO_SELF,
                1f,
                Animation.RELATIVE_TO_SELF,
                0f
            )
        val alpha = AlphaAnimation(0f, 1f)
        val set = AnimationSet(true)
        set.addAnimation(translate)
        set.addAnimation(alpha)
        return set
    }

    open fun animateShow() {
        val set = getShowAnimationSet()
        set.interpolator = DecelerateInterpolator()
        set.duration = mAnimationDuration.toLong()
        set.fillAfter = true
        animateTargetView?.startAnimation(set)
    }

    open fun getHideAnimationSet(): AnimationSet{
        val translate =
            TranslateAnimation(
                Animation.RELATIVE_TO_SELF,
                0f,
                Animation.RELATIVE_TO_SELF,
                0f,
                Animation.RELATIVE_TO_SELF,
                0f,
                Animation.RELATIVE_TO_SELF,
                1f
            )
        val alpha = AlphaAnimation(1f, 0f)
        val set = AnimationSet(true)
        set.addAnimation(translate)
        set.addAnimation(alpha)
        return set
    }

    open fun animateHide() {
        val dismissTask = Runnable {
            // java.lang.IllegalArgumentException: View=com.android.internal.policy.PhoneWindow$DecorView{22dbf5b V.E...... R......D 0,0-1080,1083} not attached to window manager
            // 在dismiss的时候可能已经detach了，简单try-catch一下
            try {
                dialogDismiss()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        if (animateTargetView?.height == 0) {
            // TranslateAnimation will not call onAnimationEnd if its height is 0.
            // At this case, we run dismiss task immediately.
            dismissTask.run()
            return
        }
        val set = getHideAnimationSet()
        set.interpolator = DecelerateInterpolator()
        set.duration = mAnimationDuration.toLong()
        set.fillAfter = true
        set.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation) {
                mIsAnimating = true
            }

            override fun onAnimationEnd(animation: Animation) {
                mIsAnimating = false
                animateTargetView?.post(dismissTask)
            }

            override fun onAnimationRepeat(animation: Animation) {}
        })
        animateTargetView?.startAnimation(set)
    }
}